<template>
  <div class="addInnovate-container-padding ">
    <div v-if="!disabled" class="buttonList">
      <el-button type="primary" @click="save">保存为草稿</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
    <div class="card">
      <!-- <div class="title">人员基本信息</div> -->
      <el-form ref="baseInfoRef" :model="userBaseInfo" :rules="rules" :disabled="disabled" label-width="auto"
        label-position="top" class="form-inline">
        <el-form-item v-for="item in formList" :key="item.label" :label="item.label" :prop="item.prop">
          <el-input v-model="userBaseInfo[item.prop]" placeholder="请输入" :rows="4" type="textarea" clearable />
        </el-form-item>
        <el-form-item label="七、相关附件和证明材料" prop="file">
          <div class="card margin-top20" v-if="!disabled">
            <div class="title">附件信息</div>
            <uploadFile @upload:success="handleUpload" :file-list="fileList" />
          </div>
          <div v-else class="card margin-top20">
            <el-link class="iLink" v-for="i in fileList" :href="i.url">{{ i.name }}</el-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, withDefaults, defineProps, onMounted, watch } from 'vue'
import type { FormRules, FormInstance, UploadUserFile } from 'element-plus'
import { useRoute } from 'vue-router'
import uploadFile from './uploadFile.vue'
import { formList } from '../table/column'
import { VxePagerEvents } from 'vxe-table'
import { addInnovate, getInnovateInfo, updateInnovate } from '@/api/innovate'
import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'
import { postDraftBoxCreate } from '@/api/project/drafts'

const props = withDefaults(
  defineProps<{
    disabled?: boolean
    userInfo?: any
  }>(),
  {
    disabled: false,
    userInfo: {},
  }
)


const route = useRoute()
const { closeTabNavigate } = useCloseTabNavigate()
const baseInfoRef = ref<FormInstance>()

const userBaseInfo = reactive({
  ducomentMaterial: ''
})
const id = ref<number>()
const fileList = ref([])

const rules = reactive<FormRules>({})

watch(
  () => props.userInfo,
  (newval) => {
    for (const key in newval) {
      userBaseInfo[key] = newval[key]
    }
    fileList.value = JSON.parse(newval.ducomentMaterial)
  },
  { deep: true }
)

const handleUpload = (data: UploadUserFile[]) => {
  userBaseInfo.ducomentMaterial = JSON.stringify(data)
}

// 保存为草稿
const save = () => {
  baseInfoRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const params = {
          id: route.query.id || '',
          type: 'CREATIVITY_PRODUCT_REPORT',
          submitJson: JSON.stringify({
            ...userBaseInfo,
            draftBoxId: route.query?.id || '',
          }),
        }
        const res: any = await postDraftBoxCreate(params)
        if (res && res.code === 0) {
          ElMessage.success('保存草稿成功')
          baseInfoRef.value.resetFields()
          closeTabNavigate({ name: 'innovate' })
        } else {
          ElMessage.error(`保存草稿失败: ${res.msg || '未知错误'}`)
        }
      } catch (e) {
        console.error('保存草稿失败', e)
      }
    }
  })
}
// 提交表单
const submit = () => {
  baseInfoRef.value.validate((valid) => {
    console.log(valid)
    if (valid) {
      if (id.value) {
        let params = {
          id: id.value,
          ...userBaseInfo,
        }
        updateInnovate(params).then(res => {
          ElMessage({
            type: 'success',
            message: '修改成功',
          })
          closeTabNavigate({ name: 'innovate' })
        })
      } else {
        addInnovate(userBaseInfo).then(res => {
          ElMessage({
            type: 'success',
            message: '新增成功',
          })
          closeTabNavigate({ name: 'innovate' })
        })
      }
    }

  })
}
onMounted(() => {
  id.value = Number(route.query.id)
  if (id.value) {
    getInnovateInfo({ id: id.value, getType: 2 }).then((res) => {
      for (const key in res.data) {
        userBaseInfo[key] = res.data[key]
        fileList.value = JSON.parse(res.data.ducomentMaterial)
      }
    })
  }
})

const tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})

const handlePageChange: VxePagerEvents.PageChange = ({
  currentPage,
  pageSize,
}) => {
  tablePage.currentPage = currentPage
  tablePage.pageSize = pageSize
  // findList()
}

const height = ref(0)
interface BaseTableHeight {
  (padding: number): number;
}
const $baseTableHeight = inject<BaseTableHeight>('$baseTableHeight')
onBeforeMount(() => {
  window.addEventListener('resize', handleHeight)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleHeight)
})

const handleHeight = () => {
  height.value = $baseTableHeight(0)
}
</script>

<style scoped lang="scss">
$margin-bottom: 20px;

.margin-left20 {
  margin-left: $margin-bottom;
}

.buttonList {
  display: flex;
  justify-content: end;
  padding-bottom: $margin-bottom;
  border-bottom: 1px solid #edeff2;
  margin-bottom: $margin-bottom;
}

.card {
  .title {
    border-radius: 2px;
    border-left: 5px solid #1890ff;
    height: 28px;
    background: #f7f8f9;
    font-weight: 500;
    font-size: 14px;
    color: #606266;
    padding-left: 12px;
    line-height: 28px;
    margin-bottom: $margin-bottom;
  }
}

.margin-bottom0 {
  margin-bottom: 0 !important;
}

.margin-top20 {
  margin-top: 20px;
}

.demo-form-inline {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-row-gap: 16px;
  grid-column-gap: 20px;

  :deep(.el-form-item__label) {
    padding: 0 5px 0 0;
  }

  :deep(.el-form-item) {
    margin-right: 0px;
    margin-bottom: 0px;
  }
}

.flexBox {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-column-gap: 20px;
}

.formCard {
  border-radius: 4px;

  .formCardtitle {
    background: #e7f3ff;
    font-size: 12px;
    color: #7d8398;
    padding-left: 10px;
    height: 24px;
    line-height: 24px;
    border-radius: 4px 4px 0 0;
  }

  .cardForm {
    background: #f6fbff;
    padding: 20px;
    border-radius: 0 0 4px 4px;

  }
}

.demo-form {
  :deep(.el-form-item__content) {
    display: block;
  }

  .el-input {
    --el-input-width: 50%;
  }

  .el-select {
    --el-select-width: 50%;
  }
}

.last {
  margin-top: $margin-bottom;
}

.form-inline {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 20px;
}

.iLink+.iLink {
  margin-top: 20px;
}
</style>
